<?php

namespace App\Admin\Eloquent;

class Permission extends Model
{
    /**
     * 实例化模型时, 可批量赋值属性白名单
     *
     * @var array
     */
    protected $fillable = [
        'name', 'methods', 'uri', 'pid', 'description', 'is_menu'
    ];

    protected $validatorRules = [
        'name'        => 'required|max:50',
        'methods'     => 'max:50',
        'uri'         => 'max:200',
        'description' => 'max:100',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Admin\Eloquent\Role', 'role_permissions', 'permission_id', 'role_id');
    }
    
    /**
     * 保存权限数据到数据库
     *
     * @param  array $options
     * @return bool
     */
    public function save(array $options = [])
    {
        Role::cleanCachedPermissions();

        return parent::save($options);
    }

    /**
     * 删除代码
     *
     * @return bool
     */
    public function delete()
    {
        Role::cleanCachedPermissions();

        foreach ($this->children as $child) {
            $child->delete();
        }

        return parent::delete();
    }

    /**
     * 当前权限父级权限
     */
    public function parent()
    {
        return $this->belongsTo('App\Admin\Eloquent\Permission', 'pid', 'id');
    }

    /**
     * 当前权限的子集权限
     */
    public function children()
    {
        return $this->hasMany('App\Admin\Eloquent\Permission', 'pid', 'id');
    }

    /**
     * 分页模糊查询
     *
     * @param  array  $options
     * @param  int  $perPage
     * @return \App\Permission[]
     */
    public static function paginateQuery(array $options = [], int $perPage = 15)
    {
        $query = static::query();

        if (isset($options['search']) && !empty($options['search'])) {
            $condition = '%' . $options['search'] . '%';

            $query = $query->where('name', 'like', $condition)
                           ->orWhere('methods', 'like', $condition)
                           ->orWhere('uri', 'like', $condition)
                           ->orWhere('description', 'like', $condition);
        }

        return $query->orderBy('created_at', 'desc')->paginate($perPage);
    }

    /**
     * 判断父级权限是否无效
     *
     * @return bool
     */
    protected function parentIsInvalid()
    {
        if (empty($this->pid)) {
            return false;
        }

        return !$this->parent()->exists();
    }

    /**
     * 追加较验规则
     *
     * @param  \Illuminate\Validation\Validator $validator
     * @return void
     */
    protected function afterValidationHook($validator)
    {
        if ($this->parentIsInvalid()) {
            $validator->errors()->add('pid', '父级权限 是无效的。');
        }
    }
}